<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Custom\Business\Order;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    use HelperControllerBuildTrait;

    protected $statusDescription = ['异常订单', '等待物流报价', '待付款', '已付款', '待收货', '已收货，待评论', '订单完成'];

    public function getIndex(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $pageSize = $request->query('pageSize', $request->pageSize);

        if ($request->ajax()) {
            $orders
                = \Auth::user()->purchaserOrders();
            if ($request->tab > 0) {
                $orders->whereStatus($request->tab);
            }

            if ($orderCode = $request->orderId) {
                $orders->where('order_code', 'like', "%$orderCode%");
            }

            if ($start = $request->startTime) {
                $orders->where('created_at', '>=', date('Y-m-d', strtotime($start)));
            }

            if ($end = $request->endTime) {
                $orders->where('created_at', '<=', date('Y-m-d', strtotime($end)));
            }

            if ($purchaser = $request->buyerName) {
                $orders->whereHas('purchaser', function ($builder) use ($purchaser) {
                    $builder->where('user', 'like', "%$purchaser%");
                });
            }

            $orders = $orders->orderBy('created_at', 'desc')->paginate($pageSize);

            $data = [
                'pagingConfData' => [
                    'page'     => $orders->currentPage(),
                    'pageSize' => $pageSize ?: 4,
                    'total'    => $orders->total() ?: 4,
                ],
            ];

            foreach ($orders as $order) {
                $data['data'][] = [
                    'orderid'         => $order->order_code,
                    'storeName'       => $order->purchaser->information->company,
                    'orderStatusTxt'  => $this->statusDescription[$order->status],
                    'orderTime'       => date('Y-m-d H:i:s', strtotime($order->created_at)),
                    'payWay'          => '#',
                    'orderTotal'      => sprintf("%.2f", $order->getTotalAmount()),
                    'orderStatusVal'  => $order->status,
                    'orderDetailHerf' => route('account.provider.order.detail', [$order->order_code]),
                    'goodsList'       => call_user_func_array(function (Order $order) {
                        $specs = $order->specifications;
                        $data  = [];
                        foreach ($specs as $spec) {
                            $data[] = [
                                'goodHref'  => '#',
                                'goodImg'   => $spec->goods_cover,
                                'goodName'  => $spec->goods_name,
                                'shortInfo' => '*',
                                'price'     => sprintf("%.2f", $spec->original_price * $spec->price_strategy),
                                'amount'    => $spec->amount,
                                'total'     => sprintf("%.2f",
                                    ($spec->original_price * $spec->price_strategy) * $spec->amount),
                            ];
                        }

                        return $data;
                    }, [$order]),
                ];
            }

            return response()->json($data);
        }

        $xrange = function () {
            for ($i = 1; $i <= 6; $i++) {
                yield $i;
            }
        };

        $data = [];

        // 全部
        $tmp            = $this->getAjaxDataList($request);
        $data['data'][] = [
            'detail'         => isset($tmp['data']) ? $tmp['data'] : [],
            'pagingConfData' => $tmp['pagingConfData'],
        ];

        foreach ($xrange() as $status) {
            $tmp            = $this->getAjaxDataList($request, $status);
            $data['data'][] = [
                'detail'       => isset($tmp['data']) ? $tmp['data'] : [],
                'pagingConfData' => $tmp['pagingConfData'],
            ];
        }

        return view('host/custom/provider/order/index')->with('orders', json_encode($data));
    }

    /**
     * 按订单状态获取列表数据
     *
     * @param Request $request
     * @param null    $status
     * @param int     $pageSize
     *
     * @return array
     */
    protected function getAjaxDataList(Request $request, $status = null, $pageSize = 4)
    {
        $pageSize = is_null($pageSize) ? $request->query('pageSize') : $pageSize;

        $orders
            = \Auth::user()->purchaserOrders();

        if (!is_null($status)) {
            $orders->whereStatus($status);
        }

        $orders = $orders->orderBy('created_at', 'desc')->paginate($pageSize);

        $data = [
            'pagingConfData' => [
                'page'     => $orders->currentPage(),
                'pageSize' => $pageSize ?: 4,
                'total'    => $orders->total() ?: 0,
            ],
        ];

        foreach ($orders as $order) {
            $data['data'][] = [
                'orderid'         => $order->order_code,
                'storeName'       => $order->purchaser->information->company,
                'orderStatusTxt'  => $this->statusDescription[$order->status],
                'orderTime'       => date('Y-m-d H:i:s', strtotime($order->created_at)),
                'payWay'          => '#',
                'orderTotal'      => sprintf("%.2f", $order->getTotalAmount()),
                'orderStatusVal'  => $order->status,
                'orderDetailHerf' => route('account.provider.order.detail', [$order->order_code]),
                'goodsList'       => call_user_func_array(function (Order $order) {
                    $specs = $order->specifications;
                    $data  = [];
                    foreach ($specs as $spec) {
                        $data[] = [
                            'goodHref'  => '#',
                            'goodImg'   => $spec->goods_cover,
                            'goodName'  => $spec->goods_name,
                            'shortInfo' => '*',
                            'price'     => sprintf("%.2f", $spec->original_price * $spec->price_strategy),
                            'amount'    => $spec->amount,
                            'total'     => sprintf("%.2f",
                                ($spec->original_price * $spec->price_strategy) * $spec->amount),
                        ];
                    }

                    return $data;
                }, [$order]),
            ];
        }

        return $data;
    }

    public function getOrderInfo(Request $request)
    {
        $id = $request->orderNo;

        $order = Order::where('order_code', $id)->firstOrFail();

        return response()->json([
            'data' => [
                'buyerName'       => $order->purchaser->user,
                'orderNo'         => $order->order_code,
                'goodsTotalPrice' => $order->total_amount,
                'distributePrice' => $order->logistics_price,
                'orderPrice'      => $order->total_amount + $order->logistics_price,
            ],
        ]);
    }

    public function putOrderInfo(Request $request)
    {
        $id = $request->orderNo;

        $order = Order::where('order_code', $id)->firstOrFail();

        // TODO 后面完善验证规则
        $order->offer($request->distributePrice, $request->goodsTotalPrice);

        $xrange = function () {
            for ($i = 1; $i <= 6; $i++) {
                yield $i;
            }
        };

        $data = [];

        // 全部
        $tmp            = $this->getAjaxDataList($request);
        $data['data'][] = [
            'detail'         => isset($tmp['data']) ? $tmp['data'] : [],
            'pagingConfData' => $tmp['pagingConfData'],
        ];

        foreach ($xrange() as $status) {
            $tmp            = $this->getAjaxDataList($request, $status);
            $data['data'][] = [
                'detail'       => isset($tmp['data']) ? $tmp['data'] : [],
                'pagingConfData' => $tmp['pagingConfData'],
            ];
        }

        return response()->json($data);
    }

    public function getDetail(Request $request, $id)
    {
        $order = Order::where('order_code', $id)->firstOrFail();

        return view('host/custom/provider/order/detail')->with('order', $order);
    }
}
